package org.example.util;


import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.example.model.vo.UserVo;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;



@Slf4j
public class JwtUtils {
    //设置过期时间
    private static final long EXPIRE_DATE = 1000 * 10 * 60 * 24; // 一天
    //token秘钥
    private static final String TOKEN_SECRET = "Zhangyue";

    public static String createToken(UserVo userVo) {

        // 过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
        // 获得JWT构造器
        JwtBuilder builder = Jwts.builder();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userId", userVo.getId());
        hashMap.put("account", userVo.getAccount());
        hashMap.put("userName", userVo.getName());
        hashMap.put("gender", userVo.getGender());
        hashMap.put("status", userVo.getStatus());
        hashMap.put("role", userVo.getRole());
        hashMap.put("roleId", userVo.getRoleId());
        hashMap.put("roleName", userVo.getRoleName());
        hashMap.put("roleStatus", userVo.getRoleStatus());
        hashMap.put("classId", userVo.getClassId());
        hashMap.put("className", userVo.getClassName());
        return builder.setSubject("hello")
                .setClaims(hashMap)
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256, TOKEN_SECRET)
                .compact();
    }


    // 获取userName
    public static Result getUserInfo(String token) {
        try {
            Jws<Claims> claimsJws
                    = Jwts.parser() // 构造器
                    .setSigningKey(TOKEN_SECRET) // 加盐
                    .parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            UserVo userVo = new UserVo();
            userVo.setId(claims.get("userId", Long.class));
            userVo.setAccount(claims.get("account", String.class));
            userVo.setName(claims.get("userName", String.class));
            userVo.setGender(claims.get("gender", String.class));
            userVo.setStatus(claims.get("status", Integer.class));
            userVo.setRole(claims.get("role", String.class));
            userVo.setRoleId(claims.get("roleId", Long.class));
            userVo.setRoleName(claims.get("roleName", String.class));
            userVo.setRoleStatus(claims.get("roleStatus", Integer.class));
            userVo.setClassId(claims.get("classId", Long.class));
            userVo.setClassName(claims.get("className", String.class));
            return Result.ok().data("user", userVo);
        } catch (ExpiredJwtException e) {
            return Result.ok().data("msg", "身份过期请重新登录").setCode(403);
        } catch (Exception e) {
            return Result.error().data("error", e.getMessage());
        }

    }

    public static <T> T toObj(String token, Class<T> clazz) {
        T t = null;
        Gson instance = GsonUtil.getInstance();
        try {
            Result result = JwtUtils.getUserInfo(token);
            Map<String, Object> data = result.getData();
            Object user = data.get("user");
            t = instance.fromJson(instance.toJson(user), clazz);
        } catch (
                JsonSyntaxException e) {
            log.error(e.getMessage());
        }
        return t;
    }

    public static void main(String[] args) {
        UserVo userVo = new UserVo();
        userVo.setAccount("123");
        userVo.setGender("男");
        userVo.setId(101L);
        userVo.setRoleId(1L);
        System.out.println(JwtUtils.createToken(userVo));
    }
}
